﻿using Microsoft.EntityFrameworkCore;
using Wms.Core.Entities;
using Wms.Data;

public class InventoryService
{
	private readonly WarehouseDbContext Db;

	public InventoryService(WarehouseDbContext db)
	{
		Db = db;
	}

	// 入库
	public async Task<bool> SaveStockInOrderAsync(StockInOrder order)
	{
		using var transaction = await Db.Database.BeginTransactionAsync();
		try
		{
			if (order.Id > 0)
			{
				var oldOrder = await Db.StockInOrders.Include(o => o.Details)
					.FirstOrDefaultAsync(o => o.Id == order.Id);

				foreach (var d in oldOrder.Details)
				{
					var inv = await Db.Inventories.FirstOrDefaultAsync(i => i.ItemId == d.ItemId && i.LocationId == d.LocationId);
					if (inv != null) inv.Quantity -= d.Quantity;
				}
				Db.StockInDetails.RemoveRange(oldOrder.Details);
			}

			if (order.Id == 0)
				Db.StockInOrders.Add(order);
			else
				Db.StockInOrders.Update(order);

			await Db.SaveChangesAsync();

			foreach (var d in order.Details)
			{
				d.StockInOrderId = order.Id;
				Db.StockInDetails.Add(d);

				var inv = await Db.Inventories.FirstOrDefaultAsync(i => i.ItemId == d.ItemId && i.LocationId == d.LocationId);
				if (inv == null)
					Db.Inventories.Add(new Inventory { ItemId = d.ItemId, LocationId = d.LocationId, Quantity = d.Quantity });
				else
					inv.Quantity += d.Quantity;
			}

			await Db.SaveChangesAsync();
			await transaction.CommitAsync();
			return true;
		}
		catch
		{
			await transaction.RollbackAsync();
			return false;
		}
	}

	// 出库
	public async Task<bool> SaveStockOutOrderAsync(StockOutOrder order)
	{
		using var transaction = await Db.Database.BeginTransactionAsync();
		try
		{
			if (order.Id > 0)
			{
				var oldOrder = await Db.StockOutOrders.Include(o => o.Details)
					.FirstOrDefaultAsync(o => o.Id == order.Id);

				foreach (var d in oldOrder.Details)
				{
					var inv = await Db.Inventories.FirstOrDefaultAsync(i => i.ItemId == d.ItemId && i.LocationId == d.LocationId);
					if (inv != null) inv.Quantity += d.Quantity;
				}

				Db.StockOutDetails.RemoveRange(oldOrder.Details);
			}

			if (order.Id == 0)
				Db.StockOutOrders.Add(order);
			else
				Db.StockOutOrders.Update(order);

			await Db.SaveChangesAsync();

			foreach (var d in order.Details)
			{
				d.StockOutOrderId = order.Id;
				Db.StockOutDetails.Add(d);

				var inv = await Db.Inventories.FirstOrDefaultAsync(i => i.ItemId == d.ItemId && i.LocationId == d.LocationId);
				if (inv == null || inv.Quantity < d.Quantity)
					throw new Exception($"物料 {d.ItemId} 库存不足");

				inv.Quantity -= d.Quantity;
			}

			await Db.SaveChangesAsync();
			await transaction.CommitAsync();
			return true;
		}
		catch
		{
			await transaction.RollbackAsync();
			return false;
		}
	}
}
